// pages/createZone/createZone.js
import login from '../../utils/login'

const app = getApp()
import lottie from 'lottie-miniprogram'
const ani = new Array(6)

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    x:0,
    y:0,
    musicList:[],
    played:true,
    isPaused:false,
    mapOfMusic:{},
    isLogin:false,
    lottieSrc:[{
        path: '../../json/rainy1.js',
        canvas: '#canvas1'
      },{
        path:'../../json/thunder.js',
        canvas:'#canvas2'
      },{
        path:'../../json/wave.js',
        canvas:'#canvas3'
      },{
        path:'../../json/fire.js',
        canvas:'#canvas4'
      },{
        path:'../../json/wind.js',
        canvas:'#canvas5'
      },{
        path:'../../json/circket.js',
        canvas:'#canvas6'
      }
    ],
    lottieIndex:[false, false, false, false, false, false],
    lottiePauseIndex:[false, false, false, false, false, false],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let login = app.globalData.isLogin
    // console.log(login)
    if(login) {
      this.setData({
        isLogin:true
      })
    }
    let that = this
    wx.request({
      url: 'https://thinker.skyseaee.com/initMusic',
      success(res){
        let ml = res.data.data
        for(let m of ml) {
          m.id = m.id-1
        }
        that.setData({
          musicList:ml
        })
        //console.log(res.data.data)
        let tmpAudioContext = new Map()
        let musicList = that.data.musicList
        for(let music of musicList) {
          let innerAudioContext = wx.createInnerAudioContext()
          // console.log(music.name, music.url.split('/')[2])
          innerAudioContext.src = 'https://thinker.skyseaee.com/audio/'+music.tmpPath.split('/')[2]
          innerAudioContext.autoplay = true
          innerAudioContext.loop = true
          innerAudioContext.volume = 0.01
          tmpAudioContext.set(music.id, innerAudioContext)
        }
        that.setData({
          mapOfMusic:tmpAudioContext
        })
        that.switchAuto2Zero()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.drawThreeJS()
    //console.log(app.globalData.updateStatus)
    if(app.globalData.updateStatus===1) {
      this.resetAuto()
      //console.log(this.data.musicList)
      app.globalData.updateStatus = 0
    }
    let login = app.globalData.isLogin
    if(login) {
      this.setData({
        isLogin:true
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    if(this.data.played)
      this.playMusic()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    for(let [_,value] of this.data.mapOfMusic) {
      value.destroy()
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  scroll(e) {

  },

  scrollToTop() {
    this.setAction({
      scrollTop: 0
    })
  },

  tap() {
    for (let i = 0; i < order.length; ++i) {
      if (order[i] === this.data.toView) {
        this.setData({
          toView: order[i + 1],
          scrollTop: (i + 1) * 200
        })
        break
      }
    }
  },

  tapMove() {
    this.setData({
      scrollTop: this.data.scrollTop + 10
    })
  },

  getid(idnum){
    for(let i=0; i<this.data.musicList.length; i++) {
      if(this.data.musicList[i].id === idnum) {
        this.setData({
          id: idnum
        })
      }
    }
  },

  selectMusic: function(event){
    let id = event.currentTarget.dataset.item.id
    // console.log(id)
    this.getid(id)
  },

  randomDesign: function(){
    let tmpList = this.data.musicList
    for(let i=0;i<tmpList.length;i++){
      let auto_new = Math.floor(Math.random()*500)
      tmpList[i].auto = auto_new
      if(auto_new>30) {
        this.initCanvas(i)
        let pause = this.data.lottiePauseIndex
        pause[i] = false
        this.setData({
          lottiePauseIndex:pause
        })
      }
    }
    let tmpMusic = this.data.mapOfMusic
    for(let [key, music] of tmpMusic) {
      for(let list of tmpList) {
        if(key===list.id) {
          music.volume = list.auto/600
        }
      }
    }
    this.setData({
      musicList:tmpList,
      isPaused:true,
      mapOfMusic:tmpMusic
    })
    wx.showToast({
      title: '随机定制完成'
    })
  },

  adjustAuto: function(event) {
    let positionx = event.changedTouches[0].pageX
    // console.log(positionx)
    let tmpList = this.data.musicList
    let tmpMusic = this.data.mapOfMusic

    if(positionx>=30 && positionx<=288) {
      let trueX = positionx*2.1-40
      tmpList[this.data.id].auto = Math.floor(trueX)
      //console.log(this.data.id)
      // console.log(tmpList[this.data.id].auto)
      tmpMusic.get(this.data.id).volume = Math.floor(trueX)/600
      this.initCanvas(this.data.id)
      this.setData({
        musicList:tmpList,
        isPaused:true,
        mapOfMusic:tmpMusic
      })
    } else if(positionx<36){
      tmpList[this.data.id].auto = 0
      tmpMusic.get(this.data.id).volume = 0
      this.setData({
        musicList:tmpList,
        isPaused:true,
        mapOfMusic:tmpMusic
      })
    } else {
      tmpList[this.data.id].auto = 562
      tmpMusic.get(this.data.id).volume = 1
      this.setData({
        musicList:tmpList,
        isPaused:true,
        mapOfMusic:tmpMusic
      })
    }
  },

  saveMusic:function(){
    let point = 0
    let map = new Map()
    //console.log(this.data.musicList)
    for(music of this.data.musicList){
      point+=music.auto
      //console.log(music)
      map.set(music.id,music.auto)
    }
    if(point<1){
      wx.showToast({
        title: '无数据可保存',
        icon:'error'
      })
      return
    }
    //console.log(point)
    let nickName = wx.getStorageSync('nickName')
    let userid = wx.getStorageSync('userid')
    let music = this.map2String(map)
    //console.log(music)
    let that = this
    wx.navigateTo({
      url: '/pages/saveMusic/saveMusic',
      success(res){
        res.eventChannel.emit('transportPara',{
          nickName:nickName,
          userid:userid,
          music:that.data.musicList
        })
      }
    })
  },

  // 将Map字符串化
  map2String(map){
    let obj = Object.create(null)
    for(let[k,v] of map){
      obj[k] = v
    }
    return JSON.stringify(obj)
  },

  resetAuto() {
    let tmpList = this.data.musicList
    for(let music of tmpList) {
      music.auto=0
    }
    let tmpMusic = this.data.mapOfMusic
    for(let [_,value] of tmpMusic) {
      value.volume = 0
      value.seek(0)
    }
    this.setData({
      musicList:tmpList,
      isPaused:true,
      mapOfMusic:tmpMusic
    })
  },

  reset(){
    let that = this
    wx.showModal({
      cancelColor: 'cancelColor',
      title:'是否重置',
      success(res){
        if(res.confirm){
          that.resetAuto()
          for(let i=0; i<6; i++) {
            that.pauseAni(i)
          }
          that.setData({
            isPaused:false,
            lottiePauseIndex:[true, true, true, true, true, true]
          })
        }else if(res.cancel){
          return
        }
      }
    })
  },

  playMusic() {
    let played = this.data.played
    let mapOfMusic = this.data.mapOfMusic
    // 播放->暂停状态
    if(played) {
      if(!this.data.isPaused) {
        for(let innerAudioContext of mapOfMusic.values()) {
          innerAudioContext.pause()
        }

        for(let i=0; i<6; i++) {
          this.pauseAni(i)
        }

        this.setData({
          lottiePauseIndex:[true, true, true, true, true, true]
        })
      }
        //innerAudioContext.pause()
      else{
        for(let innerAudioContext of mapOfMusic.values()) {
          innerAudioContext.stop()
        }
        for(let i=0; i<6; i++) {
          this.pauseAni(i)
        }

        this.setData({
          isPaused:false,
          lottiePauseIndex:[true, true, true, true, true, true]
        })
      }
    } else {
      for(let innerAudioContext of mapOfMusic.values()) {
        innerAudioContext.play()
      }
      for(let i=0; i<6; i++) {
        this.playAni(i)
      }
      this.setData({
        lottiePauseIndex:[false, false, false, false, false, false]
      })
    }

    this.setData({
      played:!played
    })
  },

  loginFun: function () {
    login.loginFun(this)
    app.globalData.isLogin = true
  },

  drawThreeJS: function () {
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#000000',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
  },

  initCanvas: function (id) {
    const that = this
    // console.log(this.data.lottiePauseIndex)
    // console.log(this.data.musicList[id].auto)
    let auto = this.data.musicList[id].auto
    if(auto>28) {
      // 如果存在动画
      if (this.data.lottieIndex[id]) {
        // 动画暂停
        if(this.data.lottiePauseIndex[id]) {
          this.playAni(id)
          let pause = this.data.lottiePauseIndex
          pause[id] = false
          this.setData({
            lottiePauseIndex:pause
          })
        }
        return
      }
      wx.createSelectorQuery().selectAll(that.data.lottieSrc[id].canvas).node(res => {
        const canvas = res[0].node
        const context = canvas.getContext('2d')
  
        canvas.width = 240
        canvas.height = 240
  
        lottie.setup(canvas)
        ani[id] = lottie.loadAnimation({
          loop: true,
          autoplay: true,
          // path:that.data.lottieSrc[id],
          animationData: require(that.data.lottieSrc[id].path),
          rendererSettings: {
            context,
          },
        })
      }).exec()
      const index = that.data.lottieIndex
      index[id] = true
      that.setData({
        lottieIndex: index
      })
    } else {
      // 如果没有Lottie动画，直接返回 
      if(!this.data.lottieIndex[id]) {
        return
      }
      // 如果未暂停，将其暂停并更新状态
      if(!this.data.lottiePauseIndex[id]) {
        this.pauseAni(id)
        let pause = this.data.lottiePauseIndex
        pause[id] = true
        // console.log('pause', pause)
        this.setData({
          lottiePauseIndex:pause
        })
      }
    }
  },

  switchAuto2Zero: function () {
    let musicMap = this.data.mapOfMusic
    for(let music of musicMap.values()) {
      music.volume = 0
    }
    this.setData({
      mapOfMusic:musicMap
    })
  },

  pauseAni(id) {
    if(ani[id]!=null)
      ani[id].pause()
  },

  playAni(id) {
    if(ani[id]!=null)
      ani[id].play()
  }
})